<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>最长公共前缀</title>
</head>

<body>

</body>
<script>
    //找出数组中最长的一项 
    function longStr(str) {
        let max = str[0];
        for (let i = 1; i < str.length; i++) {
            max = str[i].length > max.length ? str[i] : max;
        }
        return max;
    };

    function longestCommonPrefix(str) {
        let longerStr = longStr(str);
        let same = [];
        for (let i = 0; i < longerStr.length; i++) {
            let x = longerStr[i];
            let times = 0;
            for (let j = 0; j < str.length; j++) {
                if (x == str[j][i]) {
                    times++;
                }
            }
            // console.log('x', x, times);
            if (times == str.length) {
                same.push(x);
            }
            if (times != str.length) {
                break;
            }

        }
        return same.join('');

    };
    console.log(longestCommonPrefix(["carlo", "car"]));
</script>

</html>